package com.fjzx.androidframe.network.uploader;

import android.os.Handler;
import android.os.Message;


import com.fjzx.androidframe.network.callback.UploadProgressListener;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 带进度的文件请求体
 *
 * @author xiongyongcong
 */
public class ProgressRequestBody extends RequestBody {
    /**
     * 请求体
     **/
    protected RequestBody requestBody;
    /**
     * 进度回调
     **/
    protected UploadProgressListener listener;
    /**
     * 文件大小
     **/
    protected long contentLength;
    private BufferedSink bufferedSink;

    public ProgressRequestBody(RequestBody requestBody, UploadProgressListener listener) {
        this.requestBody = requestBody;
        this.listener = listener;
        try {
            this.contentLength = requestBody.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public long contentLength() throws IOException {
        return contentLength;
    }

    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        requestBody.writeTo(bufferedSink);
        bufferedSink.flush();
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            // 当前写入字节数
            long bytesWritten = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                // 增加当前写入的字节数
                bytesWritten += byteCount;
                Message msg = new Message();
                msg.obj = bytesWritten;
                mHandler.sendMessage(msg);
            }
        };
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            listener.onProgress((long) msg.obj, contentLength);
        }
    };
}
